package com.yuanqi.controller;

import com.yuanqi.domain.OrderPayment;
import com.yuanqi.domain.PaymentApplicationRequest;
import com.yuanqi.service.OrderPaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/finance/order-payments")
@CrossOrigin(origins = "*")
public class OrderPaymentController {
    
    @Autowired
    private OrderPaymentService orderPaymentService;
    
    @GetMapping
    public ResponseEntity<Map<String, Object>> getOrderPayments(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String orderType,
            @RequestParam(required = false) String orderNumber,
            @RequestParam(required = false) String paymentStatus) {
        
        try {
            Pageable pageable = PageRequest.of(page - 1, size);
            Page<OrderPayment> orderPage = orderPaymentService.getOrderPayments(pageable, orderType, orderNumber, paymentStatus);
            
            // 如果没有分页数据，使用条件查询
            if (orderPage.isEmpty() && (orderType != null || orderNumber != null || paymentStatus != null)) {
                List<OrderPayment> orders = orderPaymentService.getOrderPaymentsByConditions(orderType, orderNumber, paymentStatus);
                
                Map<String, Object> response = new HashMap<>();
                response.put("content", orders);
                response.put("totalElements", orders.size());
                response.put("totalPages", 1);
                response.put("currentPage", page);
                response.put("size", size);
                
                return ResponseEntity.ok(response);
            }
            
            // 转换实体为Map，便于前端使用
            List<Map<String, Object>> orderMaps = orderPage.getContent().stream()
                .map(this::convertOrderToMap)
                .toList();
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", orderMaps);
            response.put("totalElements", orderPage.getTotalElements());
            response.put("totalPages", orderPage.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            // 如果出错，返回模拟数据
            return ResponseEntity.ok(getMockData(page, size));
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getOrderPaymentById(@PathVariable Integer id) {
        try {
            OrderPayment order = orderPaymentService.getOrderPaymentById(id);
            if (order != null) {
                return ResponseEntity.ok(convertOrderToMap(order));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    @PostMapping("/apply")
    public ResponseEntity<Map<String, Object>> applyPayment(@RequestBody PaymentApplicationRequest paymentRequest) {
        try {
            Map<String, Object> result = orderPaymentService.applyPayment(paymentRequest);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    @PostMapping("/{id}/approve")
    public ResponseEntity<Map<String, Object>> approvePayment(@PathVariable Integer id, @RequestBody Map<String, Object> approvalData) {
        try {
            String approver = (String) approvalData.get("approver");
            String approveRemark = (String) approvalData.get("approveRemark");
            
            Map<String, Object> result = orderPaymentService.approvePayment(id, approver, approveRemark);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "审批失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    @PostMapping("/{id}/reject")
    public ResponseEntity<Map<String, Object>> rejectPayment(@PathVariable Integer id, @RequestBody Map<String, Object> rejectionData) {
        try {
            String rejector = (String) rejectionData.get("rejector");
            String rejectRemark = (String) rejectionData.get("rejectRemark");
            
            Map<String, Object> result = orderPaymentService.rejectPayment(id, rejector, rejectRemark);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "驳回失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    @PostMapping
    public ResponseEntity<Map<String, Object>> createOrder(@RequestBody Map<String, Object> orderData) {
        try {
            Map<String, Object> result = orderPaymentService.createOrder(orderData);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "创建订单失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getOrderPaymentStats() {
        try {
            Map<String, Object> stats = orderPaymentService.getOrderPaymentStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    // 私有方法：转换OrderPayment实体为Map
    private Map<String, Object> convertOrderToMap(OrderPayment order) {
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("id", order.getId());
        orderMap.put("orderType", getOrderTypeText(order.getOrderType()));
        orderMap.put("orderNumber", order.getOrderNumber());
        orderMap.put("orderDate", order.getOrderDate() != null ? order.getOrderDate().toString() : "");
        orderMap.put("supplierName", order.getSupplierCustomerName());
        orderMap.put("responsiblePerson", order.getContactPerson());
        orderMap.put("contactPhone", order.getContactPhone());
        orderMap.put("totalAmount", order.getTotalAmount());
        orderMap.put("pendingAmount", order.getPendingAmount());
        orderMap.put("status", getPaymentStatusText(order.getPaymentStatus()));
        orderMap.put("statusText", getPaymentStatusText(order.getPaymentStatus()));
        orderMap.put("remark", order.getRemark() != null ? order.getRemark() : "");
        orderMap.put("creator", order.getCreatorName());
        orderMap.put("createTime", order.getCreateTime() != null ? order.getCreateTime().toString() : "");
        return orderMap;
    }
    
    // 获取订单类型文本
    private String getOrderTypeText(Integer orderType) {
        if (orderType == null) return "";
        return orderType == OrderPayment.ORDER_TYPE_PURCHASE ? "采购单" : "退货单";
    }
    
    // 获取付款状态文本
    private String getPaymentStatusText(Integer paymentStatus) {
        if (paymentStatus == null) return "";
        switch (paymentStatus) {
            case 0: return "未付款";
            case 1: return "部分付款";
            case 2: return "已付款";
            default: return "未知状态";
        }
    }
    
    // 获取模拟数据（当真实数据不可用时）
    private Map<String, Object> getMockData(int page, int size) {
        List<Map<String, Object>> orders = List.of(
            createOrderMap(1, "采购单", "CG001", "2023-01-03", "XXX有限公司", "夏油杰", "13333333333", 5000.00, 5000.00, "partial", "部分付款", "", "夏油杰", "2024-08-23"),
            createOrderMap(2, "采购单", "CG002", "2023-01-05", "YYY贸易公司", "五条悟", "14444444444", 8000.00, 0.00, "paid", "已付款", "已完成付款", "五条悟", "2024-08-24"),
            createOrderMap(3, "退货单", "TH001", "2023-01-07", "ZZZ供应商", "伏黑惠", "15555555555", 3000.00, 3000.00, "unpaid", "未付款", "等待审批", "伏黑惠", "2024-08-25")
        );
        
        Map<String, Object> response = new HashMap<>();
        response.put("content", orders);
        response.put("totalElements", 3);
        response.put("totalPages", 1);
        response.put("currentPage", page);
        response.put("size", size);
        
        return response;
    }
    
    private Map<String, Object> createOrderMap(Integer id, String orderType, String orderNumber, String orderDate, 
                                             String supplierName, String responsiblePerson, String contactPhone,
                                             Double totalAmount, Double pendingAmount, String status, 
                                             String statusText, String remark, String creator, String createTime) {
        Map<String, Object> order = new HashMap<>();
        order.put("id", id);
        order.put("orderType", orderType);
        order.put("orderNumber", orderNumber);
        order.put("orderDate", orderDate);
        order.put("supplierName", supplierName);
        order.put("responsiblePerson", responsiblePerson);
        order.put("contactPhone", contactPhone);
        order.put("totalAmount", totalAmount);
        order.put("pendingAmount", pendingAmount);
        order.put("status", status);
        order.put("statusText", statusText);
        order.put("remark", remark);
        order.put("creator", creator);
        order.put("createTime", createTime);
        return order;
    }
}
